import { defineStore } from 'pinia';
import type { UserState } from './types';
import {
  getUserProfile,
  updateInfo,
  login as userLogin,
  logout as userLogout,
} from '@/api/user/index';
import type { LoginParams } from '@/api/user/types';
import { clearToken, setToken } from '@/utils/auth';
import FileApi from '@/api/file/index';

const useUserStore = defineStore('user', {
  state: (): UserState => ({
    id: '',
    nickname: '小牛敦敦',
    avatar: '',
    mobile: '',
    sex: 0,
    point: 0,
    experience: 0,
    level: undefined,
    brokerageEnabled: false,
    levelExpireTime: '',
    unitCount: 0,
    courseCount: 0,
  }),
  getters: {
    userInfo(state: UserState): UserState {
      return { ...state };
    },
  },
  actions: {
    // 设置用户的信息
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },
    // 重置用户信息
    resetInfo() {
      this.$reset();
    },
    // 获取用户信息
    async info() {
      const result = await getUserProfile();
      this.setInfo(result);
    },
    // 异步登录并存储token
    login(loginForm: LoginParams) {
      return new Promise((resolve, reject) => {
        userLogin(loginForm).then((res) => {
          const token = res.token;
          if (token) {
            setToken(token);
          }
          resolve(res);
        }).catch((error) => {
          reject(error);
        });
      });
    },
    // Logout
    async logout() {
      await userLogout();
      this.resetInfo();
      clearToken();
    },
    // 小程序授权登录
    // authLogin(provider: providerType = 'weixin') {
    //   return new Promise((resolve, reject) => {
    //     uni.login({
    //       provider,
    //       success: async (result: UniApp.LoginRes) => {
    //         if (result.code) {
    //           const res = await loginByCode({ code: result.code });
    //           resolve(res);
    //         }
    //         else {
    //           reject(new Error(result.errMsg));
    //         }
    //       },
    //       fail: (err: any) => {
    //         console.error(`login error: ${err}`);
    //         reject(err);
    //       },
    //     });
    //   });
    // },

    // 微信小程序手机号授权登陆
    mobileLogin(e: any) {
      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async (resolve) => {
        if (e.errMsg !== 'getPhoneNumber:ok') {
          return resolve(false);
        }

        // 1. 获得微信 code
        const codeResult = await uni.login();
        if (codeResult.errMsg !== 'login:ok') {
          return resolve(false);
        }

        // 2. 一键登录
        const loginResult = await userLogin({ phoneCode: e.code, loginCode: codeResult.code, state: 'default' });
        if (loginResult) {
          await this.info();
          return resolve(true);
        }
        else {
          return resolve(false);
        }
      });
    },

    // 选择头像（来自文件系统）
    async uploadAvatar(tempUrl: string) {
      if (!tempUrl) {
        return;
      }
      const res: any = await FileApi.uploadFile(tempUrl);
      return res.code === 0 ? res.data : '';
    },

    // 更新用户信息
    updateUserInfo(data: { nickname: string; avatar: string }) {
      updateInfo(data).then((res) => {
        if (res) {
          // 更新用户信息
          this.setInfo({
            nickname: data.nickname,
            avatar: data.avatar,
          });
          uni.showToast({
            title: '更新成功',
          });
        }
      });
    },
  },
});

export default useUserStore;
